package com.bing.Impl;

import com.bing.beans.Person;
import com.bing.exception.WeiBoException;
import com.bing.sina.SinaJdbc;
import com.bing.util.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2014/6/20.
 */

@Component
public class GetPersonStep extends AbstrcatStep {
    private static final Logger logger = LoggerFactory.getLogger(GetPersonStep.class);
    public static final int FETCH_PAGE = 10;
    private static final int WEIBO_PAGE_SIZE = 46;
    private ExecutorService executorService;
    private ExcelUtil excelUtil;
    private boolean forceUpdate;
    private List<String> weiboIds;

    @Autowired
    private SinaJdbc sinaJdbc;

    @Override
    public void preStart(Context context) {
        super.preStart(context);
        forceUpdate = (boolean) context.getSetting(Context.FORCE_UPDATE);
        weiboIds = (List<String>) context.getSetting(Context.WEIBOID);
    }

    @Override
    public void end(Context context) {
        super.end(context);
        logger.info("结束Login...........");
    }

    @Value("#{sina['step.juBaoXinxi.process']}")
    public void setProcess(Boolean process) {
        super.setProcess(process);
    }

    /**
     * 登陆淘大客,获取淘大客资料
     */
    @Override
    public void exec(Context context) {
        int count = 1;
        for (String url : weiboIds) {
            taoListener.setTitle("(" + count + "/" + weiboIds.size() + ")");
            Statistics.guanZhu.set(0);
            Statistics.weiBo.set(0);
            Statistics.fenSi.set(0);
            count++;
            try {
                Person person = sinaJdbc.findPerson(url);
                if (forceUpdate || person == null || person.isFinished() == false) {
                    executorService = Executors.newCachedThreadPool();
                    if (person == null) {
                        person = new Person();
                        person.setUrl(url);
                    } else {
                        sinaJdbc.resetPerson(person);
                    }
                    person = getPerson(person);
                    if (person == null) {
                        continue;
                    }
                    setFenSiOrGuanZhu(person, 1);
                    setFenSiOrGuanZhu(person, 2);
                    setWeiBo(person);
                    executorService.shutdown();
                    while (!executorService.awaitTermination(5l, TimeUnit.SECONDS)) {
                    }
                    ;
                    excelUtil.closeWrite();
                    person.setFinished(true);
                    sinaJdbc.savePerson(person);
                }

            } catch (Exception e) {
                logger.error("采集用户信息失败....", e);
            } finally {
            }
        }

    }

    @Autowired
    @Qualifier("endStep")
    public void setNextStep(AbstrcatStep nextStep) {
        super.setNextStep(nextStep);
    }


    private void setFenSiOrGuanZhu(Person person, int flag) {
        String leiBei;
        String url;
        if (flag == 1) {
            leiBei = "粉丝";
            url = Context.PRE_WEIBO + person.getUrl() + "/follow?relate=fans&page=";

        } else {
            leiBei = "关注";
            url = Context.PRE_WEIBO + person.getUrl() + "/follow?page=";
        }
        logger.info("开始采集{}:{}", leiBei, person.getUrl());
        String html;
        for (int i = 1; i <= FETCH_PAGE; i++) {
            for (int j = 0; j <= 3; j++) {
                try {
                    logger.info("开始采基{}:{},第{}次", leiBei, url + i, j);
                    driver.get(url + i);
                    break;
                } catch (Exception e) {
                    if (j == 3) {
                        throw new WeiBoException(Context.GetFOLLOWFAILED, e);
                    }
                }
            }
            TaoBao.pause();
            html = driver.getPageSource();
            Document doc = Jsoup.parse(html);
            Elements persons = doc.select("div.PRF_W_wrapl ul.cnfList li div.con_left");
            if (persons == null || persons.size() == 0) {
                logger.info(" 第{}页 数据量: {}", i, 0);
                return;
            } else {
                logger.info(" 第{}页 数据量: {}", i, persons.size());
            }
            executorService.execute(new FenSiOrGuanZhuParse(html, person, flag, sinaJdbc, taoListener, excelUtil));
        }


    }


    private Person getPerson(Person p) {
        for (int i = 0; i <= 3; i++) {
            logger.info("采集用户{} 信息.....尝试第{}次", p.getUrl(), i);
            try {
                driver.get(Context.PRE_WEIBO + p.getUrl());
                WebElement level = driver.findElement(By.cssSelector("div.profile_top div.pf_name div.icon_bed[node-type=level]"));
                Actions action = new Actions(driver);
                action.moveToElement(level).build().perform();
                TaoBao.pause();
                PersonParse personParse = new PersonParse(driver.getPageSource(), p, taoListener);
                personParse.run();
                excelUtil = new ExcelUtil(p.getUserName(), TaoMath.SDF_DATE_YMDHM.format(p.getCreatedTime()));
                excelUtil.writePerson(p);
                sinaJdbc.savePerson(p);
                return p;
            } catch (Exception e) {
                if (e instanceof NoSuchElementException) {
                    return null;
                }
                if (i == 3) {
                    logger.error("采集人物失败", e);
                }
            }
        }
        return null;
    }



    public void setWeiBo(Person person) {
        String url = Context.PRE_WEIBO + person.getUrl() + "/weibo?page=";
        logger.info("开始采集微薄信息.");
        for (int i = 1; i <= Math.ceil(Statistics.t_weiBo.intValue() / WEIBO_PAGE_SIZE); i++) {
            for (int j = 0; j < 3; j++) {
                try {
                    logger.info("开始采集微薄信息.{},第{}次", url + i, j);
                    driver.get(url + i);
                    TaoBao.scrollBar(driver, By.cssSelector("div.copy"));
                    TaoBao.scrollBar(driver, By.cssSelector("div.copy"));
                    break;
                } catch (Exception e) {
                    if (j == 3) {
                        throw new WeiBoException(Context.GETWEIBOFAILED, e);
                    }
                }
            }
            WeiBoParse weiBoParse = new WeiBoParse(driver.getPageSource(), person, sinaJdbc, taoListener, excelUtil);
            executorService.execute(weiBoParse);
        }
    }
}
